import { createContext, useState, useEffect, ReactNode } from 'react';

type Theme = 'light' | 'dark';

interface ThemeContextType {
  theme: Theme;
  isDark: boolean;
  toggleTheme: () => void;
}

interface ThemeProviderProps {
  children: ReactNode;
}

// 创建默认上下文值
export const ThemeContext = createContext<ThemeContextType>({
  theme: 'light',
  isDark: false,
  toggleTheme: () => {},
});

// 创建主题提供者组件
export const ThemeProvider = ({ children }: ThemeProviderProps) => {
  // 初始化主题状态
  const [theme, setTheme] = useState<Theme>(() => {
    const savedTheme = localStorage.getItem('theme') as Theme;
    if (savedTheme) {
      return savedTheme;
    }
    // 回退到用户系统的颜色偏好
    return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
  });

  // 应用主题到DOM
  useEffect(() => {
    // 移除所有主题相关的类
    document.documentElement.classList.remove('light', 'dark');
    
    // 添加当前主题类
    document.documentElement.classList.add(theme);
    
    // 设置data-theme属性，便于Tailwind识别
    document.documentElement.setAttribute('data-theme', theme);
    
    // 保存主题到本地存储
    localStorage.setItem('theme', theme);
  }, [theme]);

  // 切换主题函数
  const toggleTheme = () => {
    setTheme(prevTheme => {
      const newTheme = prevTheme === 'light' ? 'dark' : 'light';
      return newTheme;
    });
  };

  return (
    <ThemeContext.Provider value={{ theme, isDark: theme === 'dark', toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};